package main

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"laxkits/lib/laxcmdline"
	"laxkits/lib/laxproxy"
	"laxkits/lib/laxutils"
	"laxkits/lib/zlogger"
	"os"
	"strings"
)

type ROProxyXMLNode struct {
	Log             zlogger.LaxLogNode `xml:"log"`
	IgnoreProtoList []string           `xml:"ignore_proto>proto"`
	ROProtoXMLPath  string             `xml:"proto_xml_path"`
	LoginAddr       string             `xml:"login_addr"`
	PrintProtoList  []string           `xml:"print_proto>proto"`
	WebPort         int                `xml:"web_port"`
}

var globalXmlNode ROProxyXMLNode

func main() {
	if err := laxutils.LoadXmlFile("roproxy.xml", &globalXmlNode); err != nil {
		fmt.Printf("解压纳配置失败[%v]", err)
		return
	}
	trimEvent := func() {
		for i := range globalXmlNode.IgnoreProtoList {
			globalXmlNode.IgnoreProtoList[i] = strings.TrimSpace(globalXmlNode.IgnoreProtoList[i])
		}
		for i := range globalXmlNode.PrintProtoList {
			globalXmlNode.PrintProtoList[i] = strings.TrimSpace(globalXmlNode.PrintProtoList[i])
		}
		globalXmlNode.LoginAddr = strings.TrimSpace(globalXmlNode.LoginAddr)
	}
	trimEvent()
	zlogger.InitLogger(&globalXmlNode.Log)
	loadProtocolXML()
	registerProtocolParser()
	ctx, cancel := context.WithCancel(context.Background())
	// 连loginserver
	go laxproxy.NewHookProxyAndServe(ctx, 25001, &ROCodec{}, func() laxproxy.IProxyUserContext {
		return &RORoleContext{
			connectServerAddress: globalXmlNode.LoginAddr,
		}
	})
	// 连gate
	go laxproxy.NewHookProxyAndServe(ctx, kGatePort, &ROCodec{}, func() laxproxy.IProxyUserContext {
		return &RORoleContext{}
	})
	go laxproxy.GenProtoServe(ctx, globalXmlNode.WebPort, &ROCodec{})
	laxcmdline.RegisterCmdLine("reload", func(splitParams []string) string {
		globalXmlNode.IgnoreProtoList = globalXmlNode.IgnoreProtoList[0:0]
		globalXmlNode.PrintProtoList = globalXmlNode.PrintProtoList[0:0]
		if err := laxutils.LoadXmlFile("roproxy.xml", &globalXmlNode); err != nil {
			return fmt.Sprintf("加载失败:%v", err)
		}
		trimEvent()
		return "加载成功"
	})
	laxcmdline.StartCmdLine()
	zap.S().Info("启动成功")
	laxutils.CloseGracefully(func(sig os.Signal) {
		cancel()
		zap.S().Infof("进程关闭，信号[%s]", sig.String())
	})
}
